package com.chen.aba;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class ABATest {

    // 初始值为1，版本时间戳为1
    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1, 1);

    public static void main(String[] args) throws InterruptedException {

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println("a线程第一次版本号：" + stamp);

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 参数分别是：期望值、新值、期望时间戳、新时间戳
            System.out.println(atomicStampedReference.compareAndSet(1, 2, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));

            System.out.println("a线程第二次版本号：" + atomicStampedReference.getStamp());

            System.out.println(atomicStampedReference.compareAndSet(2, 1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));

            System.out.println("a线程第三次版本号：" + atomicStampedReference.getStamp());
        }).start();


        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println("b线程第一次版本号：" + stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(atomicStampedReference.compareAndSet(1, 6, stamp, stamp + 1));

            System.out.println("b线程第二次版本号：" + stamp);
        }).start();


    }

}
